package com.dmz.szsf.server;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dmz.szsf.tempuri.WebServiceBankLocator;
import com.dmz.szsf.tempuri.WebServiceBankSoapStub;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lee
 */
public class MultiThreadServer extends Thread {
    private int port = 8665;
    private ServerSocket serverSocket;
    private ExecutorService executorService;
    private int POOL_SIZE = 100;
    private int MAX_SIZE = 200;
    boolean reAccetp = true;
    private int cpuNum = 1;
    private static int count = 0;
    private long threadWait = 1000L;
    private static ReentrantLock lock = new ReentrantLock();

    public MultiThreadServer() {
        try {
            this.serverSocket = new ServerSocket(this.port);
            this.cpuNum = Runtime.getRuntime().availableProcessors();
            this.executorService = Executors.newFixedThreadPool(this.cpuNum * this.POOL_SIZE);
            System.out.println("服务器启动");
        } catch (IOException var9) {
            var9.printStackTrace();
        }

    }

    public void service() {
        while(this.reAccetp) {
            InterruptedException ex;
            if (this.getCount() < this.MAX_SIZE) {
                ex = null;

                try {
                    Socket socket = this.serverSocket.accept();
                    this.executorService.execute(new Handler(socket));
                } catch (Exception var3) {
                    var3.printStackTrace();
                }
            } else {
                try {
                    Thread.sleep(this.threadWait);
                } catch (InterruptedException var4) {
                    ex = var4;
                    ex.printStackTrace();
                }
            }
        }

    }

    public void closeServer() {
        try {
            this.reAccetp = false;
            this.serverSocket.close();
        } catch (IOException var2) {
        }

        this.executorService.shutdown();
    }


    private int getCount() {

        int ret;
        try {
            lock.lock();
            ret = count;
        } finally {
            lock.unlock();
        }

        return ret;
    }

    public void increaseCount() {
        try {
            lock.lock();
            ++count;
        } finally {
            lock.unlock();
        }

    }

    private void decreaseCount() {
        try {
            lock.lock();
            --count;
        } finally {
            lock.unlock();
        }

    }

    @Override
    public void run() {
        this.service();
    }

    class Handler implements Runnable {
        int a = MultiThreadServer.this.getCount();
        private Socket socket;

        public Handler(Socket socket) {
            this.socket = socket;
        }

        private OutputStream getOutputStream(Socket socket) throws IOException {
            OutputStream socketOut = socket.getOutputStream();
            return socketOut;
        }

        private InputStream getInputStream(Socket socket) throws IOException {
            InputStream socketIn = socket.getInputStream();
            return socketIn;
        }

        private BufferedReader getReader(Socket socket) throws IOException {
            InputStream socketIn = socket.getInputStream();
            return new BufferedReader(new InputStreamReader(socketIn));
        }

        private InputStreamReader getInputStreamReader(Socket socket) throws IOException {
            InputStream socketIn = socket.getInputStream();
            return new InputStreamReader(socketIn, "UTF-8");
        }

        public byte[] getStreamBytes(InputStream is) throws Exception {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];

            int len;
            while((len = is.read(buffer)) != -1) {
                System.out.println("读取长度" + len);
                baos.write(buffer, 0, len);
                if (is.available() <= 0) {
                    break;
                }
            }

            byte[] b = baos.toByteArray();
            baos.close();
            return b;
        }

        public String writefile(String detail, String date) throws Exception {
            JSONArray jsonArray = JSONUtil.parseArray(detail);
            int size = jsonArray.size();
            String COMPARED_FILE_PATH = "d:\\yxsf\\data\\" + date + ".txt";
            OutputStream os = new FileOutputStream(COMPARED_FILE_PATH);
            PrintWriter pw = new PrintWriter(os);

            for(int i = 0; i < size; ++i) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                pw.println(jsonObject.getStr("bankserial") + "|" + jsonObject.getStr("cuno") + "|" + jsonObject.getDouble("amount"));
                System.out.println(jsonObject.getStr("bankno") + "|" + jsonObject.getStr("bankserial") + "|" + jsonObject.getStr("paydate").replace("-", "") + "|" + jsonObject.getStr("cuno") + "|" + jsonObject.getDouble("amount"));
            }

            pw.close();
            os.close();
            return COMPARED_FILE_PATH;
        }

        public String callwsdl(String jsonStr) throws Exception {
            WebServiceBankLocator service = new WebServiceBankLocator();
            WebServiceBankSoapStub sub = (WebServiceBankSoapStub)service.getWebServiceBankSoap();
            JSONObject jb = JSONUtil.parseObj(jsonStr);
            String res = "";
            String var6;
            switch ((var6 = jb.getStr("type")).hashCode()) {
                case -1335224239:
                    if (!"detail".equals(var6)) {
                    }
                    break;
                case -339185956:
                    if ("balance".equals(var6)) {
                        res = sub.balanceTotal(jsonStr.replace(",\"type\":\"balance\"", ""));
                        JSONObject jbres2 = JSONUtil.parseObj(res);
                        if ("1".equals(jbres2.getStr("RSTCODE"))) {
                            res = "{\"RSTCODE\":1, \"RSTMSG\":\"查询成功！！！\"," + JSONUtil.toJsonStr(jbres2.getJSONArray("DATA")).replace("}]", "").replace("[{", "") + "}";
                        }
                    }
                    break;
                case 110760:
                    if ("pay".equals(var6)) {
                        res = sub.payFee(jsonStr.replace(",\"type\":\"pay\"", ""));
                    }
                    break;
                case 107944136:
                    if ("query".equals(var6)) {
                        String querystr = "{\"BankCode\":\"ZH\",\"UserCode\":\"" + jb.getStr("UserCode") + "\"}";
                        System.out.print(querystr + "\n");
                        res = sub.queryAcc(querystr);
                        JSONObject jbres = JSONUtil.parseObj(res);
                        System.out.print(jbres.getStr("RSTCODE") + "\n");
                        if ("1".equals(jbres.getStr("RSTCODE"))) {
                            res = "{\"RSTCODE\":1, \"RSTMSG\":\"查询成功！！！\"," + JSONUtil.toJsonStr(jbres.getJSONArray("DATA")).replace("}]", "").replace("[{", "") + "}";
                        }
                    }
            }

            System.out.print(res + "\n");
            return res;
        }

        @Override
        public void run() {
            MultiThreadServer.this.increaseCount();
            InputStream br = null;
            OutputStream os = null;

            try {
                Exception e;
                try {
                    System.out.println("New connection accepted " + this.socket.getInetAddress() + ":" + this.socket.getPort());
                    br = this.getInputStream(this.socket);
                    os = this.getOutputStream(this.socket);
                    e = null;
                    byte[] cspdata = this.getStreamBytes(br);
                    String cspJson = new String(cspdata);
                    System.out.println("与csp联机通信测试成功，线程退出:" + cspJson);
                    String resJson = this.callwsdl(cspJson);
                    os.write(resJson.getBytes());
                    os.flush();
                    os.close();
                    System.out.println("返回csp联机通信测试成功，线程退出:" + resJson);
                } catch (IOException var16) {
                    IOException exx = var16;
                    exx.printStackTrace();
                } catch (Exception var17) {
                    e = var17;
                    e.printStackTrace();
                }
            } finally {
                try {
                    if (this.socket != null) {
                        br.close();
                        os.close();

                        MultiThreadServer.this.decreaseCount();
                        System.out.println(this.socket.getInetAddress() + ":" + this.socket.getPort() + "--->关闭");
                        this.socket.close();
                    }
                } catch (IOException var15) {
                    var15.printStackTrace();
                }

            }

        }
    }
}
